package me.zhujin.java.learnjava.myserver.util;

/**
 * Created by zhujin on 10/20/16.
 * blog:www.zhujin.me
 * email: zhujin.nova@gmail.com
 */

import me.zhujin.java.learnjava.myserver.Const;

import javax.script.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;

public class ScriptUtil {
    private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
//    private static String msp_path=System.getProperty("user.dir")+"/";


    public static Object getHttpBody(String script_path, String method, Object... params) throws ScriptException, NoSuchMethodException, FileNotFoundException {
        String path = getAbsolutePath(script_path);
        if (path == null) return null;
        FileReader fileReader = new FileReader(path);
        engine.eval(fileReader);
        Invocable invocable = (Invocable) engine;
        return invocable.invokeFunction(method, params);
    }

    public static Object getScriptHttpBody(String script_path, Object... params) throws ScriptException, NoSuchMethodException, FileNotFoundException {
        if (script_path.substring(0, 1).equals("/")) {
            script_path = script_path.substring(1);
        }
        return getHttpBody(script_path, "index", params);
    }


    public static String getDefalutHTMLBody(String script_path) throws FileNotFoundException {
        if (script_path.substring(0, 1).equals("/")) {
            script_path = script_path.substring(1);
        }
        String path = getAbsolutePath(script_path);
        if (path == null) return null;
        return  FileUtil.readFileByLines(path);
    }


    public static String getAbsolutePath(String script_path) {
        URL url = Thread.currentThread().getContextClassLoader().getResource(script_path);
        return url == null ? null : url.getPath();
    }


    public static void main(String args[]) throws FileNotFoundException {

        System.out.printf(getDefalutHTMLBody("/msp/test.jsp"));
//        System.out.println("user_name:" + System.getProperty("user.name"));
//        System.out.println("user_home:" + System.getProperty("user.home"));
//        System.out.println("user_dir:" + System.getProperty("user.dir"));
    }
}